import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isNil from "lodash/isNil";
import _omit from "lodash/omit";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";
var _excluded = ["form", "value", "textValue", "queryParams", "queryInputProps", "style", "isButton", "isInput", "className", "isDbc2Sbc", "allowClear"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class, _class2;

import React from 'react';
import { Modal, Input, Icon, Button, message } from 'antd';
import { Bind, Throttle } from 'lodash-decorators';
import uuid from 'uuid/v4';
import intl from "../../utils/intl";
import { getResponse } from "../../utils/utils";
import LovModal from "./LovModal";
import { queryLov, queryMapIdpValue } from "../../services/api";
import "./index.less";
var defaultRowKey = 'key';
var Lov = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Throttle(500), _dec10 = Bind(), (_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(Lov, _React$Component);

  var _super = _createSuper(Lov);

  // 选中记录
  function Lov(props) {
    var _this;

    _classCallCheck(this, Lov);

    _this = _super.call(this, props);
    _this.record = undefined;
    _this.loading = false;
    _this.modalRef = {
      current: null
    };
    _this.state = {
      currentText: null,
      text: props.isInput ? props.value : props.textValue,
      textField: props.textField,
      lov: {},
      loading: false,
      ldpData: {}
    };
    _this.modalRef = React.createRef();
    return _this;
  } // eslint-disable-next-line


  _createClass(Lov, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      var _this$state = this.state,
          currentText = _this$state.currentText,
          text = _this$state.text;
      var data = {
        currentText: nextProps.textValue === currentText ? currentText : nextProps.textValue
      };

      if (currentText && currentText !== nextProps.textValue) {
        data = _objectSpread(_objectSpread({}, data), {}, {
          text: nextProps.textValue
        });
      }

      if (!text && nextProps.textValue) {
        data = _objectSpread(_objectSpread({}, data), {}, {
          text: nextProps.textValue
        });
      }

      if (nextProps.value === null || nextProps.value === undefined) {
        data = _objectSpread(_objectSpread({}, data), {}, {
          text: null
        });
      }

      if (nextProps.isInput) {
        data = _objectSpread(_objectSpread({}, data), {}, {
          text: nextProps.value
        });
      }

      this.setState(_objectSpread({}, data));
    }
  }, {
    key: "onSelect",
    value: function onSelect(record) {
      this.record = record;
    }
  }, {
    key: "selectAndClose",
    value: function selectAndClose() {
      if (!this.record) {
        Modal.warning({
          title: intl.get('cpaas.common.validation.atLeast').d('请至少选择一条数据')
        });
        return false;
      }

      this.selectRecord();
      this.setState({
        modalVisible: false
      });
    }
  }, {
    key: "getTextField",
    value: function getTextField() {
      var form = this.props.form;
      var textField = this.state.textField;

      if (form && textField) {// form.registerField(textField);
      }

      return textField;
    }
  }, {
    key: "selectRecord",
    value: function selectRecord() {
      var _this2 = this;

      var isInput = this.props.isInput;
      var _this$state$lov = this.state.lov,
          _this$state$lov$value = _this$state$lov.valueField,
          rowkey = _this$state$lov$value === void 0 ? defaultRowKey : _this$state$lov$value,
          displayName = _this$state$lov.displayField; // TODO: 值为 0 -0 '' 等的判断

      this.setState({
        text: this.parseField(this.record, displayName)
      }, function () {
        var form = _this2.props.form;

        var textField = _this2.getTextField();

        if (form && textField) {
          form.setFieldsValue(_defineProperty({}, textField, _this2.parseField(_this2.record, displayName)));
        } // 设置额外表单值


        if (form && _this2.props.extSetMap) {
          _this2.setExtMapToForm(_this2.record, _this2.props.extSetMap, form);
        }

        if (_this2.props.onChange) {
          var valueField = isInput ? displayName : rowkey;

          _this2.props.onChange(_this2.parseField(_this2.record, valueField), _this2.record);
        }

        if (_isFunction(_this2.props.onOk)) {
          _this2.props.onOk(_this2.record);
        }

        _this2.record = null;
      });
    }
    /**
     * 设置额外表单值
     * @param {Object} record 数据对象
     * @param {String} extSetMap 额外字段映射, 可以有多个, 以逗号分隔 bankId,bankName->bankDescription
     * @param {表单对象} form 表单对象
     */

  }, {
    key: "setExtMapToForm",
    value: function setExtMapToForm(record, extSetMap, form) {
      var dataSet = {};
      extSetMap.split(/\s*,\s*/g).forEach(function (entryStr) {
        var _entryStr$split = entryStr.split('->'),
            _entryStr$split2 = _slicedToArray(_entryStr$split, 2),
            recordField = _entryStr$split2[0],
            formFieldTmp = _entryStr$split2[1];

        var formField = formFieldTmp || recordField;
        form.getFieldDecorator(formField);
        dataSet[formField] = record[recordField];
      });
      form.setFieldsValue(dataSet);
    }
  }, {
    key: "onCancel",
    value: function onCancel() {
      var _this$props$onCancel = this.props.onCancel,
          onCancel = _this$props$onCancel === void 0 ? function (e) {
        return e;
      } : _this$props$onCancel;
      this.setState({
        modalVisible: false
      });

      if (_isFunction(onCancel)) {
        onCancel();
      }

      this.record = null;
    }
  }, {
    key: "showLoading",
    value: function showLoading() {
      var partialState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.setState(_objectSpread({
        loading: true
      }, partialState));
    }
  }, {
    key: "hideLoading",
    value: function hideLoading() {
      this.setState({
        loading: false
      });
    }
  }, {
    key: "modalWidth",
    value: function modalWidth(tableFields) {
      var width = 100;
      tableFields.forEach(function (n) {
        width += n.width;
      });
      return width;
    }
  }, {
    key: "onSearchBtnClick",
    value: function onSearchBtnClick() {
      var _this3 = this;

      var _this$props = this.props,
          _this$props$disabled = _this$props.disabled,
          disabled = _this$props$disabled === void 0 ? false : _this$props$disabled,
          _this$props$onClick = _this$props.onClick,
          onClick = _this$props$onClick === void 0 ? function (e) {
        return e;
      } : _this$props$onClick,
          _this$props$lovOption = _this$props.lovOptions;
      _this$props$lovOption = _this$props$lovOption === void 0 ? {} : _this$props$lovOption;
      var customValueField = _this$props$lovOption.valueField,
          customDisplayField = _this$props$lovOption.displayField;
      if (disabled || this.loading) return; // 节流

      this.record = null;
      var _this$props2 = this.props,
          viewCode = _this$props2.code,
          tenantId = _this$props2.originTenantId;
      this.loading = true;
      this.showLoading({
        loading: true,
        modalVisible: true,
        lovModalKey: uuid()
      });
      queryLov({
        viewCode: viewCode,
        tenantId: tenantId
      }).then(function (oriLov) {
        var lov = _objectSpread({}, oriLov);

        if (customValueField) {
          lov.valueField = customValueField;
        }

        if (customDisplayField) {
          lov.displayField = customDisplayField;
        }

        if (!_isEmpty(lov)) {
          var hasCode = lov.viewCode,
              _lov$title = lov.title,
              title = _lov$title === void 0 ? '' : _lov$title,
              tableFields = lov.tableFields; // 获取独立值集编码

          var valueList = lov.queryFields.filter(function (item) {
            return item.dataType === 'SELECT';
          });

          if (valueList.length > 0) {
            var valueCode = {};
            valueList.forEach(function (_ref) {
              var sourceCode = _ref.sourceCode;

              if (sourceCode) {
                valueCode[sourceCode] = sourceCode;
              }
            });
            queryMapIdpValue(valueCode).then(function (res) {
              if (getResponse(res)) {
                _this3.setState({
                  ldpData: res
                });
              }
            });
          }

          if (hasCode) {
            var width = _this3.modalWidth(tableFields);

            _this3.setState({
              lov: lov,
              title: title,
              width: width
            }, function () {
              var lovModalVisible = _this3.state.modalVisible;

              if (lovModalVisible && _this3.modalRef.current) {
                _this3.modalRef.current.loadOnFirstVisible();
              }
            });

            if (_isFunction(onClick)) {
              onClick();
            }
          } else {
            _this3.hideLoading();

            message.error(intl.get('cpaas.common.components.lov.notification.undefined').d('值集视图未定义!'));
          }
        }
      }).finally(function () {
        _this3.hideLoading();

        _this3.loading = false;
      });
    }
  }, {
    key: "searchButton",
    value: function searchButton() {
      if (this.state.loading) {
        return /*#__PURE__*/React.createElement(Icon, {
          key: "search",
          type: "loading"
        });
      }

      return /*#__PURE__*/React.createElement(Icon, {
        key: "search",
        type: "search",
        onClick: this.onSearchBtnClick,
        style: {
          cursor: 'pointer',
          color: '#666'
        }
      });
    }
  }, {
    key: "emitEmpty",
    value: function emitEmpty() {
      var _this4 = this;

      var _this$state2 = this.state,
          text = _this$state2.text,
          lov = _this$state2.lov;
      var _this$props3 = this.props,
          form = _this$props3.form,
          _this$props3$onClear = _this$props3.onClear,
          onClear = _this$props3$onClear === void 0 ? function (e) {
        return e;
      } : _this$props3$onClear,
          value = _this$props3.value,
          onChange = _this$props3.onChange;

      if (onChange) {
        var record = {};
        this.setState({
          text: ''
        }, function () {
          onChange(undefined, record);

          var textField = _this4.getTextField();

          if (form && textField) {
            form.setFieldsValue(_defineProperty({}, textField, undefined));
          }
        });
      } // TODO: 当初次进入时的情况


      if (_isFunction(onClear)) {
        var _record2;

        var _record = (_record2 = {}, _defineProperty(_record2, lov.displayField, text), _defineProperty(_record2, lov.valueField, value), _record2);

        onClear(_record);
      }
    }
    /**
     * 访问对象由字符串指定的多层属性
     * @param {Object} obj 访问的对象
     * @param {String} str 属性字符串，如 'a.b.c.d'
     */

  }, {
    key: "parseField",
    value: function parseField(obj, str) {
      if (/[.]/g.test(str)) {
        var arr = str.split('.');
        var newObj = obj[arr[0]];
        var newStr = arr.slice(1).join('.');
        return this.parseField(newObj, newStr);
      }

      return obj[str];
    }
    /**
     * 同步 Lov 值节流以提高性能
     * @param {String} value - Lov 组件变更值
     */

  }, {
    key: "setValue",
    value: function setValue(value) {
      if (this.props.onChange) {
        this.props.onChange(value);
      }
    }
    /**
     * 同步输入值至 Input 及 Lov
     * @param {String} value - 输入框内的值
     */

  }, {
    key: "setText",
    value: function setText(value) {
      var _this5 = this;

      var isInput = this.props.isInput;

      if (isInput) {
        this.setState({
          text: value
        }, function () {
          _this5.setValue(value);
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this6 = this;

      var _this$state3 = this.state,
          stateText = _this$state3.text,
          _this$state3$ldpData = _this$state3.ldpData,
          ldpData = _this$state3$ldpData === void 0 ? {} : _this$state3$ldpData;

      var _this$props4 = this.props,
          form = _this$props4.form,
          value = _this$props4.value,
          textValue = _this$props4.textValue,
          queryParams = _this$props4.queryParams,
          queryInputProps = _this$props4.queryInputProps,
          style = _this$props4.style,
          isButton = _this$props4.isButton,
          isInput = _this$props4.isInput,
          className = _this$props4.className,
          isDbc2Sbc = _this$props4.isDbc2Sbc,
          _this$props4$allowCle = _this$props4.allowClear,
          allowClear = _this$props4$allowCle === void 0 ? true : _this$props4$allowCle,
          otherProps = _objectWithoutProperties(_this$props4, _excluded);

      var textField = this.getTextField();
      var text;
      var omitProps = ['onOk', 'onCancel', 'onClick', 'onClear', 'textField', 'lovOptions'];

      if (isInput) {
        text = stateText;
        omitProps.push('onChange');
      } else {
        var texts = textField ? form && form.getFieldValue(textField) : stateText; // eslint-disable-next-line no-nested-ternary

        text = _isNil(value) ? '' : texts === 0 ? 0 : texts || textValue;
      }

      var inputStyle = isButton ? style : _objectSpread(_objectSpread({}, style), {}, {
        verticalAlign: 'middle',
        position: 'relative',
        top: -1
      });
      var isDisabled = this.props.disabled !== undefined && !!this.props.disabled;
      var showSuffix = text && allowClear && !isButton && !isDisabled;
      var suffix = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Icon, {
        key: "clear",
        className: "lov-clear",
        type: "close-circle",
        onClick: this.emitEmpty
      }), this.searchButton());
      var lovClassNames = [className, 'lov-input'];

      if (showSuffix) {
        lovClassNames.push('lov-suffix');
      }

      if (isDisabled) {
        lovClassNames.push('lov-disabled');
      }

      var _this$state4 = this.state,
          _this$state4$title = _this$state4.title,
          title = _this$state4$title === void 0 ? '' : _this$state4$title,
          _this$state4$width = _this$state4.width,
          width = _this$state4$width === void 0 ? 400 : _this$state4$width,
          _this$state4$lov = _this$state4.lov,
          lov = _this$state4$lov === void 0 ? {} : _this$state4$lov,
          modalVisible = _this$state4.modalVisible,
          loading = _this$state4.loading,
          lovModalKey = _this$state4.lovModalKey;
      var modalProps = {
        title: title,
        width: width,
        destroyOnClose: true,
        wrapClassName: 'lov-modal',
        maskClosable: false,
        onOk: this.selectAndClose,
        bodyStyle: title ? {
          padding: '16px'
        } : {
          padding: '56px 16px 0'
        },
        onCancel: this.onCancel,
        style: {
          minWidth: 400
        },
        visible: modalVisible
      };
      var _this$props5 = this.props,
          disabled = _this$props5.disabled,
          onChange = _this$props5.onChange,
          placeholder = _this$props5.placeholder;
      var inputProps = {
        disabled: disabled,
        onChange: onChange,
        placeholder: placeholder // onClick,

      };
      return /*#__PURE__*/React.createElement(React.Fragment, null, isButton ? /*#__PURE__*/React.createElement(Button, Object.assign({
        onClick: this.onSearchBtnClick,
        disabled: this.props.disabled
      }, otherProps, {
        style: style,
        className: lovClassNames.join(' ')
      })) :
      /*#__PURE__*/
      // ts-ignore
      React.createElement(Input, Object.assign({
        readOnly: !isInput // addonAfter={this.searchButton()}
        ,
        value: text,
        style: inputStyle // Lov 组件垂直居中样式，作用于 ant-input-group-wrapper
        ,
        suffix: suffix,
        onChange: function onChange(e) {
          _this6.setText(e.target.value);
        }
      }, _omit(inputProps, omitProps), {
        className: lovClassNames.join(' ')
      })), /*#__PURE__*/React.createElement(Modal, modalProps, /*#__PURE__*/React.createElement(LovModal, {
        key: lovModalKey,
        lov: lov,
        ldpData: ldpData,
        queryParams: queryParams,
        queryInputProps: queryInputProps,
        onSelect: this.onSelect,
        onClose: this.selectAndClose,
        lovLoadLoading: loading,
        wrappedComponentRef: this.modalRef,
        isDbc2Sbc: isDbc2Sbc // lovLoadLoading={loading}

      })));
    }
  }]);

  return Lov;
}(React.Component), _class2.displayName = 'Lov', _class2), (_applyDecoratedDescriptor(_class.prototype, "onSelect", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "onSelect"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "selectAndClose", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "selectAndClose"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onCancel", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "onCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "modalWidth", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "modalWidth"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onSearchBtnClick", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "onSearchBtnClick"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "emitEmpty", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "emitEmpty"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "parseField", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "parseField"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "setValue", [_dec8, _dec9], Object.getOwnPropertyDescriptor(_class.prototype, "setValue"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "setText", [_dec10], Object.getOwnPropertyDescriptor(_class.prototype, "setText"), _class.prototype)), _class));
export { Lov as default };